package fun.stgoder.test1.source;

import java.util.Arrays;

public class TestArrayListSource {

    public static void main(String[] args) {
        SimpleArrayList<Integer> simpleArrayList = new SimpleArrayList<>(4);
        simpleArrayList.add(0);
        simpleArrayList.add(1);
        simpleArrayList.add(2);
        simpleArrayList.add(3);

        System.out.println(simpleArrayList);

        System.out.println("get [2]: " + simpleArrayList.get(2));

        simpleArrayList.add(4);
        simpleArrayList.add(5);

        System.out.println("add [4],[5]: " + simpleArrayList);

        simpleArrayList.remove(4);
        System.out.println("remove [4]: " + simpleArrayList);

        System.out.println("size: " + simpleArrayList.size());

        simpleArrayList.remove(4);
        System.out.println("remove [4]: " + simpleArrayList);

        System.out.println("size: " + simpleArrayList.size());

        Integer[] integers = simpleArrayList.toArray(Integer[].class);
        System.out.println("toArray: ");
        for (Integer integer : integers) {
            System.out.println(integer);
        }
    }
}

class SimpleArrayList<E> {
    private int initLen;
    private Object[] array;
    private int size;

    public SimpleArrayList(int initLen) {
        this.initLen = initLen;
        this.array = new Object[initLen];
    }

    public void add(E e) {
        if (size < array.length - 1) {
            array[size] = e;
        } else {
            Object[] tmpArr = new Object[array.length + initLen];
            for (int i = 0; i < array.length; i++) {
                tmpArr[i] = array[i];
            }
            tmpArr[size] = e;
            array = tmpArr;
        }
        size++;
    }

    public E get(int i) {
        if (i > size - 1)
            throw new ArrayIndexOutOfBoundsException();
        return (E) array[i];
    }

    public void remove(int i) {
        if (i > size - 1)
            throw new ArrayIndexOutOfBoundsException();
        for (int j = size - 1; j > i; j--) {
            Object e = array[j];
            array[j - 1] = e;
        }
        size--;
    }

    public int size() {
        return size;
    }

    public E[] toArray(Class<? extends E[]> newType) {
        E[] res = Arrays.copyOfRange(array, 0, size, newType);
        return res;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < size; i++) {
            stringBuilder.append(array[i]).append(',');
        }
        return stringBuilder.toString();
    }

}
